import request from '@/request';
import storage from '@/commons/storage';
import store from '@/store';
import { isEmpty, isNotEmpty } from '@/commons/utils';

/**
 * 获取URL中的参数
 * @param {*} name
 */
export const getUrlParam = params => {
    const arrPara = params.split('&');
    let result = {};
    for (let i = 0; i < arrPara.length; i++) {
        let arr = arrPara[i].split('=');
        result[arr[0]] = arr[1];
    }
    return result;
};

/**
 * 根据scene获取参数信息
 * @param {*} scene
 * @param {*} type
 * @param {*} isSet 是否设置shopId缓存
 */
export const getParamsBySceneHook = async (scene = '', type = 1, isSet = true) => {
    const res = await request('getSceneInfoServ', {
        scene,
        type
    });

    const arrPara = res.data.params.split('&');
    let result = {};
    for (let i = 0; i < arrPara.length; i++) {
        let arr = arrPara[i].split('=');
        result[arr[0]] = arr[1];
    }

    if (isNotEmpty(result.shopId) && isSet) {
        storage.set('ZW_SHOP_ID', Number(result.shopId));
    }

    return result;
};

/**
 * 静默登陆获取用户openid
 */
export const loginWxinfoHandler = async () => {
    return new Promise(resolve => {
        uni.login({
            success: async res => {
                const loginCode = res.code;
                const ret = await request('loginWxinfoServ', {
                    loginCode,
                    grantType: 2
                });
                const { openid, unionid } = ret.data;
                storage.set('openid', openid);
                storage.set('unionid', unionid);
                resolve(ret.data);
            }
        });
    });
};

/**
 * 游客注册
 */
export const touristLoginHandler = async options => {
    // 设置tenantId
    await getCorpInfo();
    // 已经游客注册过不需要重复调用
    if (storage.get('userCode')) {
        return;
    }

    // 优先获取openid，避免首页埋点再次获取
    let openid = storage.get('openid');
    let unionid = storage.get('unionid');
    if (isEmpty(openid)) {
        const res = await loginWxinfoHandler();
        openid = res.openid;
        unionid = res.unionid;
    }

    // 没有shopId说明是正常进入小程序，在首页单独设置
    let shopId = options?.query?.shopId || storage.get('ZW_SHOP_ID');
    // 分享弹窗生成的二维码跳转的
    if (options?.query?.scene) {
        const res = await getParamsBySceneHook(options?.query?.scene);
        shopId = res?.shopId;
    }
    if (isEmpty(shopId)) {
        return;
    }
    storage.set('ZW_SHOP_ID', Number(shopId));

    const ret = await request('loginWxTouristServ', {
        wxOpenId: openid,
        wxUnionId: unionid
    });
    if (ret.data?.userCode) {
        storage.set('userCode', ret.data?.userCode);
    }
};

/**
 * 优先处理前置必要参数
 * @param {*} options
 */
export const setPreOptions = options => {
    const shopId = options.query?.shopId;
    if (isNotEmpty(shopId)) {
        storage.set('ZW_SHOP_ID', Number(shopId));
    }
};

/**
 * 获取企业基本信息
 */
export const getCorpInfo = async () => {
    try {
        // let shopId = storage.get('ZW_SHOP_ID');
        const res = await request('shopIdServ');
        const tenantId = res.data.tenantInfo.tenantId;
        const corpId = res.data.tenantInfo.tenantId;
        // if (isEmpty(shopId)) {
        //     shopId = res.data.shopList[0]?.id;
        // }
        // storage.set('ZW_SHOP_ID', shopId);
        storage.set('ZW_TENANT_ID', tenantId);
        storage.set('ZW_CORP_ID', corpId);
        return res.data;
    } catch (error) {
        return error;
    }
};

/**
 * 获取TabBar导航信息
 */
export const getTabBarInfo = async () => {
    const useTabBarStore = store.useTabBarStore();
    const { data } = await request('getTabBarInfoServ', {
        shopId: storage.get('ZW_SHOP_ID')
    });
    useTabBarStore.list = data.options;
};

/**
 * 处理小程序参数。（目前只处理支付小程序中 navigateBackMiniProgram 中返回的 extraData)
 * extraData.action: pay_mp_cancel支付取消，pay_mp_fail支付失败，pay_mp_success支付成功
 * @param {Object} option 页面参数
 */
export const checkQueryData = option => {
    const orderSn = option.referrerInfo?.extraData?.orderSn;
    const action = option.referrerInfo?.extraData?.action;
    const payActionStore = store.payActionStore();
    if (orderSn && orderSn === payActionStore.orderSn) {
        payActionStore.action = action || '';
    } else {
        payActionStore.action = '';
    }
};

/**
 * type="nickname"的输入框，获取隐私协议input @touchstart.stop绑定以下写法,传入focus对象{value: false}，同时绑定:focus="focus.value"
 * @param focus focus对象{value: false}
 */
export const handleTouchInput = focus => {
    if (wx.requirePrivacyAuthorize) {
        wx.requirePrivacyAuthorize({
            /**
             *
             * @param res
             */
            success: res => {
                // 用户同意了隐私协议
                focus.value = true;
            },
            /**
             *
             * @param res
             */
            fail: res => {
                // 用户拒绝了隐私协议
                focus.value = false;
            }
        });
    } else {
        focus.value = true;
    }
};
